<?php

namespace app\common\model;

use app\api\service\TokenService;
use app\common\library\AuthUtil;
use fast\Random;
use think\Cookie;
use think\Db;
use think\Exception;
use think\Model;
use think\Session;

class User extends Model
{
    protected $hidden = [
        'id','mp_id','openid','union_id','password','salt',
        'prevtime','joinip','loginfailure','loginip','logintime',
        'jointime','createtime','updatetime','remark','status',];
    protected $autoWriteTimestamp = true;
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    protected static $instance = null;
    private $_logined = FALSE;
    private $_user = NULL;
    private $keeptime = 3600 * 1;
    private $requestUri = '';

    public function saveInfo($data)
    {
        // 检测OpenId是否存在
        $this->_user = self::getByOpenid($data['openid']);
        if ($this->_user)
        {
            $this->error = 'openid already exist';
        }else{
            $ip = request()->ip();
            $time = time();
            $params = array_merge($data, [
                'mp_id'    => get_api_applet_id(),
                'salt'      => Random::alnum(),
                'jointime'  => $time,
                'joinip'    => $ip,
                'logintime' => $time,
                'loginip'   => $ip,
                'prevtime'  => $time,
                'status'    => 'normal',
            ]);

            //账号注册时需要开启事务,避免出现垃圾数据
            Db::startTrans();
            try
            {
                $ret = self::create($params);
                Db::commit();
                // 此时的Model中只包含部分数据
                $this->_user = self::get($ret);
                $this->loginByOpenId($data['openid']);
            }
            catch (Exception $e)
            {
                $this->error = $e->getMessage();
                Db::rollback();
                return ['_code'=>500,'msg'=>$this->error];
            }
        }
        return ['data'=>$this->_user];
    }

    public function loginByOpenId($openId)
    {
        if(empty($openId))
            return ['_code'=>400,'msg'=>'OpenID不能为空'];
        $this->_user = self::getByOpenid($openId);
        if(empty($this->_user))
            return ['_code'=>400,'msg'=>'用户不存在'];
        //增加登录次数和设置最后登录时间
        $this->_saveToken();
        return ['data'=>$this->_user];
    }

    /**
     * 注册用户
     * @param string $username  用户名
     * @param string $password  密码
     * @param string $email     邮箱
     * @param string $mobile    手机号
     * @param string $extend    扩展参数
     * @return boolean
     */
    public function register($data)
    {
        // 检测用户名或邮箱、手机号是否存在
        if (User::getByOpenid($data['openid']))
        {
            $this->error = 'openid already exist';
            return FALSE;
        }
        if (isset($data['mobile']) && User::getByMobile($data['mobile']))
        {
            $this->error = 'Mobile already exist';
            return FALSE;
        }

        $ip = request()->ip();
        $time = time();
        $config = get_addon_config('user');

        $user = [
            'level'    => $config['level'],
            'score'    => $config['score'],
            'avatar'   => $config['avatar'],
        ];
        $params = array_merge($data, [
            'nickname'  => $username,
            'salt'      => Random::alnum(),
            'jointime'  => $time,
            'joinip'    => $ip,
            'logintime' => $time,
            'loginip'   => $ip,
            'prevtime'  => $time,
            'status'    => 'normal'
        ]);
        $params['password'] = AuthUtil::encryptPassword($password, $params['salt']);
        $params = array_merge($params, $extend);

        ////////////////同步到Ucenter////////////////
        if (defined('UC_STATUS') && UC_STATUS && $sync)
        {
            $uc = new \addons\ucenter\library\client\Client();
            $user_id = $uc->uc_user_register($username, $password, $email);
            // 如果小于0则说明发生错误
            if ($user_id <= 0)
            {
                $this->setError($user_id > -4 ? 'Username is incorrect' : 'Email is incorrect');
                return FALSE;
            }
            else
            {
                $params['id'] = $user_id;
            }
        }

        //账号注册时需要开启事务,避免出现垃圾数据
        Db::startTrans();
        try
        {
            $ret = $this->_user->save($params);
            Db::commit();

            // 此时的Model中只包含部分数据
            $this->_user = $this->_user->get($this->_user->id);

            return $this->syncLogin();
        }
        catch (Exception $e)
        {
            $this->error = $e->getMessage();
            Db::rollback();
            return FALSE;
        }
    }

    /**
     * 保存令牌
     * @author 清凉Tea <973110519@qq.com>
     */
    private function _saveToken()
    {
        // 写入登录Session和Token
        $oldToken = $this->_user->token;
        $token = Random::uuid();
        $this->_user->save([
            'prevtime'  => $this->_user->logintime,
            'logintime' => time(),
            'token'     => $token,
            'loginip'   => request()->ip(),
        ]);
        //设置登录标识
        $this->_logined = TRUE;
        $userInfo = [
            'user_id' => $this->_user->id,
            'nickname' => $this->_user->nickname,
            'openid' => $this->_user->openid,
            'token' => $token,
        ];
        (new TokenService())->cacheSession($oldToken,$userInfo);
    }

}
